﻿/// <reference path="../typings/tsd.d.ts" />
/// <reference path="app.d.ts" />
/*
scope.me.trigger('beforeCellEdited', [upKv, $input]);
scope.me.trigger('cellEdited', [upKv, $input]);
scope.me.trigger('afterCellEdited', [upKv, $input, true]);//或 false表示失败
trigger('loaded'); trigger("reloaded");
 me.trigger("hide"  me.trigger("show"
*/
$(function () {
    //var USERINFO = {
    //    NAME: 'fgs',
    //    YHJB: '9',
    //    YHDWDM: '1',
    //    YHCDM: null,
    //    YHXM: '分公司用户',
    //    YHROLE: 'fgs'
    //};
    var USERINFO = {
        NAME: '厂',
        YHJB: '3',
        YHDWDM: '31300008',
        YHCDM: null,
        YHXM: '厂用户',
        YHROLE: 'cyc'
    };
    let $tt = $("#tt"), $ny = $("#txtNy"), $dwlist = $("#selDw"), $btnQuery = $("#btnQuery"),
        $btnSave = $("#btnCalc");
    //从请求中，获取编号及年月
    var querystring = window.location.search;
    let BBH = (querystring.match(/bbh=(\w+)/))[1];  //编号必须有
    if (/ny=(\w+)/.test(querystring)) {
        window.CXNY = querystring.match(/ny=(\w+)/)[1];
    }
    $ny.val(window.CXNY).autoDate('ny', { endDate: new Date(parseInt(window.CXNY) / 100, parseInt(window.CXNY) % 100 - 1, 2) }); //设置截止年月

    //全局的监控，
    let bbhArray = [], BBHINDEX; //顺序保存报表目录的编号
    for (var fl in window.FGSBBFL) {
        bbhArray = bbhArray.concat(window.FGSBBFL[fl]);
    }
    BBHINDEX = bbhArray.indexOf(BBH); //查询表编号
    let LOCK = true;  //当月报表是否锁定
    let CXDWDM = ''; //当前查询单位的代码
    //离开之前，判断当前页有没有计算 
    let EditCount = 0; //用户修改的次数
    function validEditCount() {
        EditCount > 0 && $.auto.alert('提示', "尚未保存修改的指标，请先保存！");
        return !EditCount;
    }
    //移到全局监控
    let HIDEFIELDS = ''; //待隐藏的列


    ////加载用户自定义的设置
    let USERCONFIG = $.auto.storage.get("USERCONFIG");
    if (_.isNull(USERCONFIG)) {
        USERCONFIG = { SH: { showShsm: true, expendAfterSave: true, editColor: '#ffeeee' } };
        $.auto.storage.set("USERCONFIG", USERCONFIG);
    }
    if (USERCONFIG.SH.editColor != "#ffeeee") {
        var style = "<style id='styEditcolor'> #tt .autoEditinput {background-color: " + USERCONFIG.SH.editColor + "!important;}</style>";
        $("head").append($(style));
    }
    $("#inpEditcolor").spectrum({
        color: USERCONFIG.SH.editColor,
        //cancelText: "取消",
        //chooseText: "选择",
        showInitial: true,
        showButtons: false,
        showPalette: true,
        palette: [["#ffeeee", "#fff2cc", "#d9ead3", "#d0e0e3"]],
        move: function (color) {
            USERCONFIG.SH.editColor = color.toHexString();
            $.auto.storage.set("USERCONFIG", USERCONFIG);
            $("#styEditcolor").html("#tt .autoEditinput {background-color: " + USERCONFIG.SH.editColor + "!important;}");
        }
    });
    $("#divBbsm").on("click", 'dt', function () {
        $("#divBbsm").find("dd").toggle(USERCONFIG.SH.showShsm = !USERCONFIG.SH.showShsm);
        $.auto.storage.set("USERCONFIG", USERCONFIG);
    });

    let isDone = true;//修改数据是否已完成
    $("#tt").on("beforeCellEdited", function () {
        isDone = false;
    });
    $("#tt").on("afterCellEdited", function () {
        isDone = true;
    });
    //修改单元格计数,增加修改记录
    $("#tt").on("cellEdited", function (e, upKv, $input) {
        EditCount++;
        $("#span_editCount").text(EditCount);
    });
    //执行查询,1、校验编辑项，2、请求（请求包含锁定、报表及签字内容）
    $btnQuery.on('click', function () {
        if (validEditCount()) {
            //设置CXNY,同时判断各种标志，准备参数
            window.CXNY = $ny.val();
            CXDWDM = $dwlist.val();
            $("#spanNY").text(window.CXNY.substring(0, 4) + "年" + window.CXNY.substring(4) + "月");
            var ny = parseInt(window.CXNY),
                shbz = "'1'",
                nyfw;  //包含的年月范围，
            if ($("#btnShowPreMonth").data("on")) {//求上月的月份。如果1月，则不求上月。
                if (ny % 100 > window.SETTING.bblx) {
                    nyfw = "'" + ny + "','" + (ny - window.SETTING.bblx) + "'";
                }
                else {
                    nyfw = "'" + ny + "','" + (ny - window.SETTING.bblx - 88) + "'";
                }
            }
            else {
                nyfw = "'" + ny + "'";
            }
            if ($("#btnShowYTHZ").data("on")) {  //判断审核标志
                shbz = "'1','0'";
            }
            var view = window.SETTING.view;
            if (!$("#btnShowNullData").attr("disabled") && (!$("#btnShowNullData").data("on"))) { //当时该表是可以显示空行的表
                view = window.SETTING.fltview;
            }
            //传入参数，请求数据及锁定、签名
            $.ajax('/api/SHCXBB/QUERY', {
                data: {
                    view: view,
                    //bbh: BBH,
                    ny: ny,
                    nyfw: nyfw,
                    cxdwdm: CXDWDM,
                    shbz: shbz,
                    //yhdwdm: USERINFO.YHDWDM,
                    //yhjb: USERINFO.YHJB,
                    //cdm: USERINFO.YHCDM,
                    //table: window.SETTING.table
                },
                dataType: 'json',
                type: 'POST',
                cache: false
            }).done(function (info) {
                var OriginOpt = $tt.data('OriginData')._opt || window.tblOption;
                //判断锁定
                if (info.locked) {
                    LOCK = true;  //特地增加全局变量，监控是否锁定
                    OriginOpt.editOn = function () { return false; };
                } else {
                    LOCK = false;
                    OriginOpt.editOn = window.Old_editOn;
                }
                //判断季报/半年报
                var dqMonth = ny % 100;
                if (dqMonth % window.SETTING.bblx != 0) {
                    OriginOpt.editOn = function () { return false; }
                    OriginOpt.data = [];
                    $tt.autoTable(OriginOpt);
                    return;
                }
                $tt.width(window.SETTING.width);
                //加载报表
                OriginOpt.data = info.data;
                $tt.autoTable(OriginOpt);
            });
        }
    });
    //重新计算,必须在用户修改完单元格后，再执行计算。
    function funCalc(flag, btn) {
        if (!isDone) {
            setTimeout(function () { funCalc(flag, btn); }, 100);
        }
        else {
            $("#img_loading").show();
            $.ajax('/api/shcxbb/bbjs', {
                data: {
                    ny: window.CXNY,
                    yhdwdm: USERINFO.YHDWDM,
                    table: window.SETTING.table,
                    bbh: BBH,                    //校验需要,
                    calcflag: flag
                },
                dataType: 'json',
                type: 'POST',
                cache: false
            }).done(function (data) {
                EditCount = 0;
                $("#span_editCount").text(EditCount);
                $("#btnQuery").click();
                if (data.length > 0) {  //如果有校验错误，则显示
                    $("#tbl_jy").autoTable({
                        data: data,
                        header: [
                            [{ title: '序号', span: [1, 1] }, { title: '年月', span: [1, 1] }, { title: '单位', span: [1, 1] }, { title: '分类', span: [1, 1] }, { title: '校验描述', span: [1, 1] }, { title: '校验左值', span: [1, 1] }, { title: '校验右值', span: [1, 1] }]
                        ],
                        isFooter: true,
                        isPageable: false,
                        isRownumber: true,
                        mergeFields: [],
                        isSaveable: true
                    });
                    $('#tbl_jy').dialog({ title: '校验结果', area: "80%" });
                    toastr.error('校验有误，请检查数据！');
                } else {
                    toastr.success('保存成功！');
                }
                $("#img_loading").hide();
            })
        }
    }

    //执行计算
    $btnSave.on('click', function () {
        setTimeout(function () { funCalc(0, $("#btnCalc")); }, 100);
    });
    //全部计算，之后合并一下数据
    $("#btnCalcAll").click(function () {
        setTimeout(function () { funCalc(1, $("#btnCalcAll")); }, 100);
        return false;
    });
    //非当前月,汇总数据都要变色.  单月查询时，隐藏年月列。 加载后，滚动到表的左上角
    $tt.on("loaded reloaded", function () {
        //遍历每一个tr
        $tt.children("tbody").children("tr:not(.autoheader2)").each(function (i, tr) {
            var $tr = $(tr);
            //非当前查询月 或汇总行
            ($tr.data("ny") != window.CXNY || $tr.data("shbz") == '0') && $tr.css({ 'background-color': '#F9F9F9' });
            //是汇总数据。虽然采集行才汇总，但厂、分公司的也应该能穿透才行。
            if ($tr.data("shbz") == '0' ) {
                //增加穿透提示
                $tr.children(':not(.frzTd)').each(function (i, td) {
                    var $td = $(td);
                    _.includes(window.tblOption.editFields, $td.data('field')) && $td.addClass('sql_ct');
                });
            }
        });
        //如果是查单月的报表，则隐藏年月列，同时把colgroup，tfood均减少一个。
        if (!($("#btnShowPreMonth").data("on") && (parseInt(window.CXNY) - 1) % 100)) {
            $tt.trigger("hide", 'NY');
        }
        /*else {
            //否则col要显示。因为col在reload时，是不变化的。所以要自己控制
            $tt.trigger("show", 'NY');
        }*/
        //触发tblDiv的scroll事件
        $("#tblDiv").scrollTop(0).scrollLeft(0);
    });
    //如果当月报表未锁定，ctrl+s在编辑的情况下，保存并计算指标.
    $(window).keydown(function (e) {
        //ctrl+s
        if (e.keyCode == 83 && e.ctrlKey) {
            e.preventDefault();
            if (!LOCK) {
                $(e.target).blur();
                setTimeout(function () {
                    $("#btnCalc").click();
                }, 100);
            }
        }
    });
    //穿透点击，穿透的五个参数： v_ny,     v_dwdm,    v_bmc,         v_fl,        v_zdm,  
    //                          行上       行上     setting.table     行上     td的data-field
    $tt.on("click", '.sql_ct', function () {
        var $td = $(this);
        var $tr = $td.parent();
        var ny = $tr.data('ny'), dwdm = $tr.data('dwdm'), bmc = window.SETTING.table, zdm = $td.data('field');

        var keyfield:any = _.difference(window.tblOption.keydataOnRow, ['NY', 'SHBZ', 'DWDM', 'TJJB']);
        var fl;
        if (keyfield.length == 1) {
            keyfield = keyfield[0].toLowerCase();
            fl = `${keyfield}='${$tr.data(keyfield)}'`;
        } else {
            fl = "无";
        }
        //跳窗口即可，传入bbpro_tj_ct(ny,dwdm,bmc,fl,zdm,ret),ret是返回的结果集。
        //var url = '/api/sh/sql_ct?ny=' + ny + '&dwdm=' + dwdm + '&bmc=' + bmc + '&fl=' + fl + '&zdm=' + zdm;
        $.ajax('/api/SHCXBB/sql_ct', {
            data: {
                ny: ny, dwdm: dwdm, bmc: bmc, fl: fl, zdm: zdm
            },
            dataType: 'json',
            type: 'POST',
            cache: false
        }).done(function (data) {
            if (data.length) {
                $("#tbl_ct").autoTable({
                    data: data,
                    isPageable: true,
                    isScrollable: true,
                    freezeContainer: '#div_ct',
                    isSaveable: true
                });
                $("#div_ct").dialog({ title: '指标详情', area: '90%' });
            }
            else {
                $.auto.alert("提示", "未穿透到指标原始数据！");
            }
        });
    });
    //用于重设置显隐按钮上的data值
    var toggleMe = function (me) {
        var on = !me.data("on");
        me.data("on", on).text(on ? "显" : "隐");
        return on;
    };
    var getSwitchOption = function (selector: string) {
        return {
            onText: '显', offText: '隐', size: 'mini',
            onSwitchChange: function (e, state) {
                if (validEditCount()) {
                    toggleMe($(selector));
                    $btnQuery.click();
                }
            }
        };
    };
    //状态面板的各个按钮功能
    $("#divState").on("click", "button", function () {
        var $this = $(this);
        var id = $this[0].id;
        if (id == "btnShowPanel") $("#divStatePanel").toggle();
        else if (_(id).startsWith("btnShow")) {
            $("#" + id.replace("btn", "chk")).bootstrapSwitch('toggleState');
        }
    });
    $("#chkShowPreMonth").bootstrapSwitch(getSwitchOption("#btnShowPreMonth"));
    $("#chkShowYTHZ").bootstrapSwitch(getSwitchOption("#btnShowYTHZ"));
    $("#chkShowColumn").bootstrapSwitch(_.extend(getSwitchOption("#btnShowColumn"), {
        onSwitchChange: function (e, state) {
            if (toggleMe($("#btnShowColumn"))) {  //全显示
                $tt.trigger("show", HIDEFIELDS);
            }
            else {
                $tt.trigger("hide", HIDEFIELDS);
            }
        }
    }));
    $("#chkShowNullData").bootstrapSwitch(getSwitchOption("#btnShowNullData"));
    //每次查询之后
    $tt.on("loaded", function () {
        if (!$("#btnShowColumn").attr("disabled")) { //当时该表是可以隐藏列的表
            if (!$("#btnShowColumn").data("on")) {
                $tt.trigger("hide", HIDEFIELDS);
            }
        }
    });
    //分页面板  
    $("#divPage").on("click", "button", function () {
        var $this = $(this);
        if ($this.hasClass("disabled")) return;
        var id = $this[0].id;
        var flag = false; //用于监视BBHINDEX有没有变化
        switch (id) {
            case "btnShowPagePanel":  //展开状态面板
                $("#divPagePanel").toggle();
                break;
            case "btnPre":
                if (validEditCount()) {
                    if (BBHINDEX >= 1) {
                        BBHINDEX--;
                        BBH = bbhArray[BBHINDEX]
                        flag = true;
                    }
                }
                break;
            case "btnNext":
                if (validEditCount()) {
                    if (BBHINDEX <= bbhArray.length - 2) {
                        BBHINDEX++;
                        BBH = bbhArray[BBHINDEX]
                        flag = true;
                    }
                }
                break;
        }
        $("#btnPre").toggleClass("disabled", (BBHINDEX == 0));
        $("#btnNext").toggleClass("disabled", (BBHINDEX == bbhArray.length - 1));
        flag && LoadBBh();
    });
    var tmplPage = _.template('<div><%=title%>(<%= arr.length %>)</div>\
<div>\
    <% for(var i=0;i<arr.length;i++) { %>\
        <button class="btn btn-sm btn-default" data-bbh="<%=arr[i]%>"><%=arr[i].replace("b","表")%></button>\
    <% } %>\
</div>');
    var strContent = "";
    for (var fl in window.FGSBBFL) {
        strContent += tmplPage({ title: fl, arr: window.FGSBBFL[fl] });
    }
    $("#divPageContent").append(strContent)
        .on("click", "button", function () {
            if (validEditCount()) {
                BBH = $(this).data("bbh");
                BBHINDEX = bbhArray.indexOf(BBH);
                LoadBBh();
                $("#divPagePanel").hide();
            }
        }).find(".btn").each(function (i, dom) {
            var bbh = $(dom).data("bbh");
            $(dom).attr("title", !!window.FGSBT[bbh] ? window.FGSBT[bbh].title.replace(/<[^>]+>/g, "") : '');
            _.includes(["b01", "b121", "b122", "b14", "b15"], bbh)
                && $(dom).text("*" + $(dom).text()).css("color", "grey");
        });
    //#divwindow.SETTING 之外点击时，隐藏那两个面板
    $("body").click(function (event) {
        if (!$.contains($("#queryDiv")[0], event.target)) {
            $("#divwindow.SETTING .absolute-hide").hide();
        }
    });

    //年月、单位、展示方式变化时，相应查询
    $("#txtNy,#selDw").change(function () {
        if (validEditCount()) {
            var OriginOpt = $tt.data('OriginData');
            OriginOpt._opt.pageNumber = 1;
            $tt.data('OriginData', OriginOpt);
            $btnQuery.click();
        } else {
            $ny.val(window.CXNY);
            $dwlist.val(CXDWDM);
        }
    });
    //全屏,toastr
    $("#btnFullScreen").click(function () {
        $("#div4fullscreen").screenfull();
    });
    //模拟填报
    if (USERINFO.YHJB == '9') {
        $("#grpMNTB").hide();
    } else {
        $("#btnMNTB").click(function () {
            if ($("#btnShowYTHZ").data("on")) {  //判断审核标志
                var $inputs = $("input.waitEdit", "#tt");
                if ($inputs.length == 0) return;
                var timer = 1;
                $.each($inputs, function (i, dom) {
                    var $ipt = $(dom);
                    var index = $ipt.parent().data("index");
                    var $preRow = $ipt.parents("tr").prev();
                    var hzVal: any = $preRow.find('td[data-index=' + index + ']').text();
                    hzVal = hzVal == "" ? null : parseFloat(hzVal);
                    var val = $ipt.val();
                    val = val == "" ? null : parseFloat(val);
                    if (hzVal != val) {
                        setTimeout(function () {
                            $ipt.val(hzVal).trigger("blur");
                        }, 300 * (timer++));
                    }
                });
            }
            else {
                $.auto.alert("错误", "模拟填报时，必须显示汇总的数据行！")
            }
        });
        //模拟填报说明
        $("#btnMNTBSM").click(function () {
            $("#div_mntbsm").dialog({
                title: '模拟填报功能说明',
                area: ['600px', '420px']
            });
        });
    }
    $(window).resize(function () {
        $("#tblDiv").css({
            height: ($(window).innerHeight() - $("#tblDiv").offset().top - 10) + 'px',
            width: (($(window).innerWidth() - 20) + 'px')
        });
    }).resize();



    //加载表编辑，做成可重入的
    //这里面的绑定事件都要加上， .shbbEvent
    function LoadBBh() {
        $tt.data('OriginData', false); //清除现在的信息
        $tt.off("shbbEvent");          //清除原有事件

        window.SETTING = window.FGSBT[BBH];
        $("#h_title").html(window.SETTING.title + '  数据审核');
        $("#divBbsm").html(window.SETTING.shsm)
            .find("dd").toggle(USERCONFIG.SH.showShsm);
        window.tblOption = window.SETTING.tblOption;
        window.SETTING.tblEditOption.editTable = window.SETTING.table;
        window.tblOption = $.extend(window.tblOption, window.SETTING.tblEditOption);
        window.Old_editOn = window.tblOption.editOn;   //保存当前表的可编辑行的规则
        $tt.width(window.SETTING.width);

        //判断显示列和空数据行是否可点击
        if (!_.isEmpty(window.tblOption.header2)) {
            HIDEFIELDS = '';
            $("#btnShowColumn").attr("disabled", "disabled");
            $("#chkShowColumn").bootstrapSwitch("toggleDisabled");
        } else {
            //HIDEFIELDS = _.difference(window.tblOption.headerFields, window.tblOption.editFields).join(",").concat(window.tblOption.editKeyFields);
            HIDEFIELDS = _(window.tblOption.headerFields).difference(window.tblOption.editFields).difference(window.tblOption.editKeyFields).difference(['DWMC']).join(",");

            $("#btnShowColumn").removeAttr("disabled");
            $("#chkShowColumn").bootstrapSwitch('disabled', false);
        }
        if (!_.includes(["b021", "b022", "b031", "b032", "b14", "b141", "b142",
            "b08", "b15", "b151", "b152", "b16"], BBH)) {
            $("#btnShowNullData").attr("disabled", "disabled");
            $("#chkShowNullData").bootstrapSwitch("toggleDisabled");
        }
        else {
            $("#btnShowNullData").removeAttr("disabled");
            $("#chkShowNullData").bootstrapSwitch('disabled', false);
        }

        //在请求单位下拉后，执行查询
        $.ajax('/api/SHCXBB/DWLIST', {
            data: {
                table: window.SETTING.table, yhdwdm: USERINFO.YHDWDM, yhjb: USERINFO.YHJB
            },
            dataType: 'json',
            type: 'POST',
            cache: false
        }).done(function (a) {
            $dwlist.html($.map(a, function (n) {
                return '<option value="' + n.DWDM + '">' + n.DWMC + '</option>';
            }).join());
            //立即查询
            $btnQuery.click();
        });

        //在多级统计行的表，则双击其中一行，则过滤掉其它数据行。
        if (window.tblOption.freezeFields.length == 4) {
            var filterfield = _.difference(window.tblOption.freezeFields, ['_rownum', 'NY', 'DWMC'])[0];
            $tt.on("dblclick.shbbEvent", ".tt_" + filterfield, function () {
                var filtervalue = $(this).text();
                var OriginData = $("#tt").data('OriginData');
                var opt = $.extend(true, {}, OriginData._opt);
                opt.filter = function (r) {
                    return r[filterfield] == filtervalue;
                }
                $("#tt").autoTable(opt).data('OriginData', OriginData);
            });
        }

    }
    LoadBBh();

});
